//
//  DataStatisticsFilterViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/25.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "DataStatisticsFilterViewController.h"
#import "OneLineWithInfoCell.h"
#import <CustomIOSAlertView.h>
#import "ProvinceData.h"
#import "SelectionNationViewController.h"
#import "SelectProvinceViewController.h"
#import "SelectCityViewController.h"
#import "StatisticsResultViewController.h"
#import "AppDelegate.h"

@interface DataStatisticsFilterViewController () {

}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,assign) long long startTime;
@property (nonatomic,assign) long long endTime;
@property (nonatomic,strong) NSString *filterArea;
@property (nonatomic,strong) UIDatePicker *datePicker;


/**
 *  选择国家、省份、城市后，保存的数据，单选
 */
@property (nonatomic,strong) NSMutableArray *selectedNation;
@property (nonatomic,strong) NSMutableArray *selectedProvince;
@property (nonatomic,strong) NSMutableArray *selectedCity;


@end

@implementation DataStatisticsFilterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self loadData];
    [self setupViews];
    
}

/**
 *  初始化数据
 */
- (void)initData {
    //获取上一个月的时间 直接减去30天
    long long number = 24*60*60*1000;
    self.startTime = [DateTools getCurrentTicket] - 30*number;
    self.endTime = [DateTools getCurrentTicket];
    self.filterArea = @"未设置";
    self.selectedNation = [NSMutableArray new];
    self.selectedProvince = [NSMutableArray new];
    self.selectedCity = [NSMutableArray new];
}

#pragma mark - 加载数据
/**
 *  加载视图所有的数据
 */
- (void)loadData {

}


#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"数据过滤";
    
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.height - KAction_Bar_Height - kNavigation_Bar_Height - kStatus_Bar_Height, kScreen_Width, KAction_Bar_Height)];
    footerView.backgroundColor = CM_BOTTOM_RIGHT_ACTION_BG_COLOR;
    [self.view addSubview: footerView];
    
    UIButton *viewBtn = [[UIButton alloc]initWithFrame:CGRectMake(20, 0, kScreen_Width - 40, KAction_Bar_Height/2)];
    [viewBtn setTitle:@"查看统计结果" forState:UIControlStateNormal];
    [viewBtn setBackgroundColor:CM_BOTTOM_RIGHT_ACTION_BG_COLOR];
    viewBtn.titleLabel.font = [UIFont systemFontOfSize:kNavTitleFontSize];
    [viewBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    viewBtn.centerY = footerView.height/2;
    [viewBtn addTarget:self action:@selector(viewStatisticsResult) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:viewBtn];
    
    
    //列表
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, self.view.height - kNavigation_Bar_Height - kStatus_Bar_Height - KAction_Bar_Height) style:UITableViewStyleGrouped];
    self.tableView.backgroundView = [[UIView alloc]init];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

#pragma mark - 事件响应
- (void)viewStatisticsResult {
    if (self.selectedNation.count == 0) {
        [Tools showMessageCenter:@"请选择需要筛选的区域！"];
        return;
    }
    StatisticsResultViewController *view = [StatisticsResultViewController new];
    view.sid = self.templeteId;
    view.tf = [DateTools getYearMonthDay:self.startTime];
    view.tt = [DateTools getYearMonthDay:self.endTime];
    view.TempleteName = self.templeteName;
    
    if (self.selectedCity.count > 0) {
        ProvinceData *data = [self.selectedCity objectAtIndex:0];
        view.rid = data.guidId;
        view.area = data.name;
    }
    else if (self.selectedProvince.count > 0) {
        ProvinceData *data = [self.selectedProvince objectAtIndex:0];
        view.rid = data.guidId;
        view.area = data.name;
    }
    else if (self.selectedNation.count > 0) {
        ProvinceData *data = [self.selectedNation objectAtIndex:0];
        view.rid = data.guidId;
        view.area = data.name;
    }
    
    [self.navigationController pushViewController:view animated:YES];
    
}


#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return 3;
    }
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //报价
    static NSString *identifier2 = @"filterCell";
    OneLineWithInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier2];
    if (cell == nil) {
        cell = [[OneLineWithInfoCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier2];
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (indexPath.section == 0 && indexPath.row == 0) {
        //开始时间
        [cell setTitleStr:@"开始时间" andInfoStr:[DateTools getYearMonthDay:self.startTime] andInfoAlignment:NSTextAlignmentCenter];
    }
    else if (indexPath.section == 0 && indexPath.row == 1) {
        //结束时间
        [cell setTitleStr:@"结束时间" andInfoStr:[DateTools getYearMonthDay:self.endTime] andInfoAlignment:NSTextAlignmentCenter];
    }
    else if (indexPath.section == 1){
        //区域过滤
        
        if (indexPath.row == 0) {
            NSMutableString *detail = [NSMutableString new];
            if (self.selectedNation && self.selectedNation.count > 0) {
                
                for (ProvinceData *item in self.selectedNation) {
                    [detail appendString:item.name];
                    [detail appendString:@" "];
                }
            }
            [cell setTitleStr:@"选择统计国家" andInfoStr:detail andInfoAlignment:NSTextAlignmentCenter];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        else if (indexPath.row == 1) {
            NSMutableString *detail = [NSMutableString new];
            if (self.selectedProvince && self.selectedProvince.count > 0) {
                for (ProvinceData *item in self.selectedProvince) {
                    [detail appendString:item.name];
                    [detail appendString:@" "];
                }
            }
            [cell setTitleStr:@"选择统计省份" andInfoStr:detail andInfoAlignment:NSTextAlignmentCenter];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        else {
            NSMutableString *detail = [NSMutableString new];
            if (self.selectedCity && self.selectedCity.count > 0) {
                for (ProvinceData *item in self.selectedCity) {
                    [detail appendString:item.name];
                    [detail appendString:@" "];
                }
            }
            [cell setTitleStr:@"选择统计城市" andInfoStr:detail andInfoAlignment:NSTextAlignmentCenter];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        //滑动按钮
        cell.rightUtilityButtons = [self rightButtons];
        cell.delegate = self;
        cell.tag = indexPath.row;

    }
    return cell;
}

-(NSArray *)rightButtons {
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"取消选择"];
    return rightUtilityButtons;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        //区域过滤
        if (indexPath.row == 0) {
            //选择国家
            SelectionNationViewController *view = [SelectionNationViewController new];
            view.selectedData = [NSMutableArray arrayWithArray:self.selectedNation];
            view.couldMultipleSelect = NO;
            view.userSelectedBlock = ^(NSMutableArray *selectedData) {
                if (self.selectedNation == nil) {
                    self.selectedNation = [NSMutableArray new];
                }
                if (selectedData.count > 0) {
                    [self.selectedNation removeAllObjects];
                    [self.selectedNation addObjectsFromArray:selectedData];
                    [self.tableView reloadData];
                    
                }
            };
            [self.navigationController pushViewController:view animated:YES];
            
        }
        else if (indexPath.row == 1) {
            //选择省份
            if (self.selectedNation == nil || self.selectedNation.count == 0) {
                kTipAlert(@"请先选择国家");
                return;
            }
            SelectProvinceViewController *view = [SelectProvinceViewController new];
            view.selectedNation = [NSMutableArray arrayWithArray:self.selectedNation];
            view.selectedData = [NSMutableArray arrayWithArray:self.selectedProvince];
            view.couldMultipleSelect = NO;
            view.userSelectedBlock = ^(NSMutableArray *selectedData) {
                if (self.selectedProvince == nil) {
                    self.selectedProvince = [NSMutableArray new];
                }
                if (selectedData.count > 0) {
                    if (self.selectedCity != nil) {
                        [self.selectedCity removeAllObjects];
                    }
                    [self.selectedProvince removeAllObjects];
                    [self.selectedProvince addObjectsFromArray:selectedData];
                    [self.tableView reloadData];
                    
                }
            };
            [self.navigationController pushViewController:view animated:YES];
        }
        else {
            //选择城市
            if (self.selectedProvince == nil || self.selectedProvince.count == 0) {
                kTipAlert(@"请先选择省份");
                return;
            }
            SelectCityViewController *view = [SelectCityViewController new];
            view.selectedProvince = [NSMutableArray arrayWithArray:self.selectedProvince];
            view.selectedData = [NSMutableArray arrayWithArray:self.selectedCity];
            view.couldMultipleSelect = NO;
            view.userSelectedBlock = ^(NSMutableArray *selectedData) {
                if (self.selectedCity == nil) {
                    self.selectedCity = [NSMutableArray new];
                }
                if (selectedData.count > 0) {
                    [self.selectedCity removeAllObjects];
                    [self.selectedCity addObjectsFromArray:selectedData];
                    [self.tableView reloadData];
                    
                }
            };
            [self.navigationController pushViewController:view animated:YES];
        }

    }
    else {
        [self chooseDate:@"选择日期" andRow:indexPath.row];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier2 = @"filterCell";
    OneLineWithInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier2];
    if (cell == nil) {
        cell = [[OneLineWithInfoCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier2];
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return [cell getHeight];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 40)];
    headView.backgroundColor = [UIColor whiteColor];
    UILabel *label;
    if (section == 0) {
        label = [UILabel labelSingleLineFontSize:kNavTitleFontSize content:@"统计时间设置"];
    }
    else {
        label = [UILabel labelSingleLineFontSize:kNavTitleFontSize content:@"统计区域设置"];
    }
    label.textColor = [UIColor blackColor];
    label.x = 2*CELL_PADDING_LEFT;
    if (section == 0) {
        label.centerY = headView.height/2 + kStatus_Bar_Height;
    }
    else {
        label.centerY = headView.height/2;
    }
    [headView addSubview:label];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 40 + kStatus_Bar_Height;
    }
    return 40;
}

-(void)chooseDate:(NSString*) title andRow:(NSInteger)row{
    CustomIOSAlertView *alert = [[CustomIOSAlertView alloc] init];
    [alert setUseMotionEffects:YES];
    alert.tag = row;
    
    UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width-50, 200)];
    
    //标题栏
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, subView.width, 50)];
    [titleView setUserInteractionEnabled:YES];
    
    titleView.backgroundColor = CM_ACTION_CELL_COLOR;
    [subView addSubview:titleView];
    //左上角、右上角圆角为7
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:titleView.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(7, 7)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = titleView.bounds;
    maskLayer.path = maskPath.CGPath;
    titleView.layer.mask = maskLayer;
    
    //添加文字
    UILabel *titleLabel = [UILabel labelSingleLineFontSize:14 content:title];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.centerY = titleView.centerY;
    titleLabel.centerX = titleView.centerX;
    [titleView addSubview:titleLabel];
    
    //选择日期
    
    self.datePicker = [[UIDatePicker alloc] init];
    self.datePicker.datePickerMode = UIDatePickerModeDate;
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中文显示
    self.datePicker.locale = locale;
    if (row == 0) {
        self.datePicker.date = [DateTools getNSDate:self.startTime];
    }
    else {
        self.datePicker.date = [DateTools getNSDate:self.endTime];
    }
    
    
    if (self.datePicker.superview == nil) {
        //此处将Y坐标设在最底下，为了一会动画的展示
        self.datePicker.frame = CGRectMake(0, titleView.height, subView.width, 150);
        [subView addSubview:self.datePicker];
    }
    
    [alert setContainerView:subView];
    [alert setButtonTitles:@[@"确定", @"取消"]];
    [alert setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex) {
            case 1:
                
                break;
            case 0:
            {
                NSDate *selectedDate = self.datePicker.date;
                if (alertView.tag == 0) {
                    self.startTime = [selectedDate timeIntervalSince1970]*1000;
                }
                else {
                    self.endTime = [selectedDate timeIntervalSince1970]*1000;
                }
                [self.tableView reloadData];
            }
                break;
            default:
                break;
        }
    }];
    
    [alert show];
    
}


#pragma mark - 滑动按钮代理协议
/**
 *  右侧滑动按钮点击事件
 *
 *  @param cell  单元cell
 *  @param index 下标
 */
-(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index{
    switch (index) {
        case 0:{
            CMLog(@"cell.tag = %ld", (long)cell.tag);
            if (cell.tag == 0) {
                //国家
                [self.selectedNation removeAllObjects];
                [self.selectedProvince removeAllObjects];
                [self.selectedCity removeAllObjects];
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:0 inSection:1], [NSIndexPath indexPathForRow:1 inSection:1], [NSIndexPath indexPathForRow:2 inSection:1],nil] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
            else if (cell.tag == 1){
                [self.selectedProvince removeAllObjects];
                [self.selectedCity removeAllObjects];
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:1 inSection:1], [NSIndexPath indexPathForRow:2 inSection:1],nil] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
            else {
                [self.selectedCity removeAllObjects];
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:2 inSection:1]] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
            break;
        }
            
        default:
            break;
    }
    [cell hideUtilityButtonsAnimated:YES];
}


/**
 *  滑动的时候把其他的隐藏掉
 *
 *  @param cell cell
 *
 *  @return 隐藏其他的cell
 */
-(BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell{
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
